<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Infotech Ltd.
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: vshoor $ ($Date: 2007/01/31 16:50:51 $)
// $RCSfile: client_chatloop.php,v $ : $Revision: 1.24 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

$template->loadLanguageSection("livesupportclient");

require_once ("./modules/livesupport/functions_livesupport.php");

// Get the chat object data
$_chatobject = getChatObjectFromSession($_REQUEST["chatsessionid"]);

if ($_chatobject["chatobjectid"] == "")
{
	// Stop the loop right here.
	$noloop = true;

	$messagejs .= "displayNewLine();".SWIFT_CRLF;
	$messagejs .= "displayMessage(\"". $_SWIFT["language"]["chatexpired"] ."\");".SWIFT_CRLF;
}

// Update both the visitor and chat session id on shutdown, visitorsessionid needs to be updated to make sure chat runs fine even if visitor closes all other browser windows
$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."sessions` SET `lastactivity` = '". DATENOW ."' WHERE `sessionid` IN('". $dbCore->escape($_REQUEST["chatsessionid"]) ."', '". $dbCore->escape($_REQUEST["sessionid"]) ."');");


/**
* ###############################################
* START ROUND ROBIN CODE
* ###############################################
*/
$timeretry = $_chatobject["roundrobintimeline"]+$_SWIFT["settings"]["livesupport_roundrobintimetry"];
if (DATENOW >= $timeretry && $_chatobject["isproactive"] != 1)
{
//	$messagejs .= "window.parent.headerframe.displayNewLine();".SWIFT_CRLF;
//	$messagejs .= "window.parent.headerframe.displayMessage(\"Triggering Round Robin\");".SWIFT_CRLF;
	$doRoundRobin = true;
}

// Is user in CHAT_INCOMING mode and all roundrobin retries have failed?
if ($_chatobject["chatstatus"] == CHAT_INCOMING && $_chatobject["roundrobinhits"] >= $_SWIFT["settings"]["livesupport_roundrobinretries"] && $doRoundRobin == true)
{
	// Seems like no staff answered this persons query, poor soul.. must be pissed at the company!.. nevertheless lets just redirect him to leave a message form now he can vent his anger on the company ;)
	$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."chatobjects` SET `chatstatus` = '". CHAT_NOANSWER ."' WHERE `chatobjectid` = '". $dbCore->escape($_chatobject["chatobjectid"]) ."';");
	$redirectleavemessage = true;
} else if ($_chatobject["chatstatus"] == CHAT_INCOMING && $doRoundRobin == true) {
	// We need to try to switch over the staff, maybe the current staff is busy drinking his coffee?
//	$messagejs .= "window.parent.headerframe.displayNewLine();".SWIFT_CRLF;
//	$messagejs .= "window.parent.headerframe.displayMessage(\"Current Staff: ". $_chatobject["staffid"] ."\");".SWIFT_CRLF;
	$newstaffid = getRoundRobinStaff($_chatobject["departmentid"], array($_chatobject["staffid"]));
//	$messagejs .= "window.parent.headerframe.displayNewLine();".SWIFT_CRLF;
//	$messagejs .= "window.parent.headerframe.displayMessage(\"Round Robin: $newstaffid\");".SWIFT_CRLF;
	if ($newstaffid)
	{
		// We need to update the staff, seems like there are other staff online too
		$newstaffname = $_SWIFT["staffcache"][$newstaffid]["fullname"];
//		$messagejs .= "window.parent.headerframe.displayNewLine();".SWIFT_CRLF;
//		$messagejs .= "window.parent.headerframe.displayMessage(\"Round Robin: $newstaffname\");".SWIFT_CRLF;

		$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."chatobjects` SET `staffid` = '". $dbCore->escape($newstaffid) ."', `staffname` = '". $dbCore->escape($newstaffname) ."', `roundrobinhits` = `roundrobinhits`+1, `roundrobintimeline` = '". DATENOW ."' WHERE `chatobjectid` = '". $dbCore->escape($_chatobject["chatobjectid"]) ."';");
	} else {
		$dbCore->shutdownQuery("UPDATE `". TABLE_PREFIX ."chatobjects` SET `roundrobinhits` = `roundrobinhits`+1, `roundrobintimeline` = '". DATENOW ."' WHERE `chatobjectid` = '". $dbCore->escape($_chatobject["chatobjectid"]) ."';");
	}

	$roundrobinexec = true;
}
/**
* ###############################################
* END ROUND ROBIN CODE
* ###############################################
*/


/**
* ###############################################
* START MESSAGE FETCHING CODE
* ###############################################
*/
$messagelistids = $staffignoreids = array();
$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."messagequeue` WHERE `chatchildid` = '". "0" ."' AND `chatobjectid` = '". $dbCore->escape($_chatobject["chatobjectid"]) ."' ORDER BY `dateline` ASC;");
while ($dbCore->nextRecord())
{
	$messagelistids[] = $dbCore->Record["messagequeueid"];
	$msgarray = unserialize($dbCore->Record["contents"]);
	if (is_array($msgarray)) {
		if ($msgarray["type"] == ACTION_MSG)
		{
			if (!in_array($dbCore->Record["staffid"], $staffignoreids))
			{
				$staffignoreids[] = $dbCore->Record["staffid"];
			}
			if ($_SWIFT["settings"]["ls_depname"] == 1 && !empty($_SWIFT["departmentcache"][$_chatobject["departmentid"]]["title"]))
			{
				$_chatname = $_SWIFT["departmentcache"][$_chatobject["departmentid"]]["title"];
			} else {
				$_chatname = $dbCore->Record["name"];
			}
			$messagejs .= "displayStaffMessage(\"". addslashes($_chatname) ."\", \"". addslashes(str_replace("\n", "<BR />", preg_replace("#(\r\n|\r|\n)#s", "\n", htmlspecialchars(iif($msgarray["base64"]==true, $msgarray["contents"], base64_encode($msgarray["contents"])))))) ."\"); \n";
		} else if ($msgarray["type"] == ACTION_URL) {
			$messagejs .= "pushURL(\"".addslashes(urldecode($msgarray["contents"])) ."\"); \n";
		} else if ($msgarray["type"] == ACTION_IMAGE) {
			$messagejs .= "pushImage(\"".addslashes($msgarray["contents"]) ."\"); \n";
		} else if ($msgarray["type"] == ACTION_CODE) {
			$messagejs .= "pushStart();".SWIFT_CRLF;
			$messagejs .= HTML2JS(highlightCode($msgarray["contents"]), "pushCode");
			$messagejs .= "pushEnd();".SWIFT_CRLF;
		} else if ($msgarray["type"] == ACTION_CHATLEAVE) {
			// Staff left the chat from conference
			$messagejs .= "displayNewLine();".SWIFT_CRLF;
			$messagejs .= "displayMessage(\"". addslashes(sprintf($_SWIFT["language"]["chatleave"], $msgarray["contents"])) ."\");".SWIFT_CRLF;
		} else if ($msgarray["type"] == ACTION_CHATENTER) {
			// Staff entered the chat for conference
			$messagejs .= "displayNewLine();".SWIFT_CRLF;
			$messagejs .= "displayMessage(\"". addslashes(sprintf($_SWIFT["language"]["chatenter"], $msgarray["contents"])) ."\");".SWIFT_CRLF;
		} else if ($msgarray["type"] == ACTION_TYPING) {
			if ($_SWIFT["settings"]["ls_depname"] == 1 && !empty($_SWIFT["departmentcache"][$_chatobject["departmentid"]]["title"]))
			{
				$_typingname = $_SWIFT["departmentcache"][$_chatobject["departmentid"]]["title"];
			} else {
				$_typingname = $msgarray["contents"];
			}

			$_typingstaff = $dbCore->Record["staffid"];
		} else if ($msgarray["type"] == ACTION_VIEWSHARE) {
			$messagejs .= "startViewShare(\"".addslashes($msgarray["contents"]["url"]) ."\"); \n";
		}
		
	}
}

if (count($messagelistids) > 0)
{
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."messagequeue` WHERE `messagequeueid` IN (". buildIN($messagelistids) .");");	
}
/**
* ###############################################
* END MESSAGE FETCHING CODE
* ###############################################
*/

// ======= User is Typing Check =======
if (!empty($_typingname))
{
	// If we just received a message from the same staff then dont display user is typing, its a tricky little way to make it a bit more realtime but hey it works..
	if (!in_array($_typingstaff, $staffignoreids))
	{
		$istyping = true;
		$messagejs .= "doUserTyping(\"". addslashes($_typingname) ."\");".SWIFT_CRLF;
	}	
}

if ($istyping == false)
{
	$messagejs .= "if (resetUserTyping) { resetUserTyping(); }".SWIFT_CRLF;
}
// ======= End User is Typing Check =======

?>
	if (!doClientLoop)
	{
		
	} else {

	<?php
	if ($redirectleavemessage == true)
	{
		?>
		parent.window.location.href = "<?php echo $_SWIFT["swiftpath"]; ?>visitor/index.php?_m=livesupport&_a=startclientchat&sessionid=<?php echo $_REQUEST["sessionid"]; ?>&leavemessage=1&departmentid=<?php echo $_chatobject["departmentid"]; ?>";	
		<?php
	} else if ($roundrobinexec == true) {
		?>
		displayMessage("<?php echo $_SWIFT["language"]["alloperatorsbusy"];?>");	
		<?php
	}

	if ($_chatobject["chatstatus"] != "")
	{
	?>

	if (chatstatus == <?php echo CHAT_INCOMING; ?> && <?php echo $_chatobject["chatstatus"]; ?> == <?php echo CHAT_INCHAT; ?>)
	{
		// Seems like staff just accepted the chat
		if (browsercode == "SF")
		{
			parent.contentframe.clearContentDiv();
		} else {
			clearDoc();
		}
		chatstatus = <?php echo CHAT_INCHAT; ?>;
		<?
		if ($_SWIFT["settings"]["ls_depname"] == 1 && !empty($_SWIFT["departmentcache"][$_chatobject["departmentid"]]["title"]))
		{
			?>
			displayMessage("<?php echo sprintf($_SWIFT["language"]["joinedchatdep"], $_chatobject["departmenttitle"]); ?>");
			<?
		} else {
			?>
			displayMessage("<?php echo sprintf($_SWIFT["language"]["joinedchat"], $_chatobject["staffname"], $_chatobject["departmenttitle"]); ?>");
			<?
		}
		?>
	}

	if (chatstatus == <?php echo CHAT_INCOMING; ?> && <?php echo $_chatobject["chatstatus"]; ?> == <?php echo CHAT_NOANSWER; ?>)
	{
		parent.window.location.href = "<?php echo $_SWIFT["swiftpath"]; ?>visitor/index.php?_m=livesupport&_a=startclientchat&sessionid=<?php echo $_REQUEST["sessionid"]; ?>&leavemessage=1&departmentid=<?php echo $_chatobject["departmentid"]; ?>";
	}

	if (chatstatus == <?php echo CHAT_INCHAT; ?> && <?php echo $_chatobject["chatstatus"]; ?> == <?php echo CHAT_ENDED; ?>)
	{
		chatstatus = <?php echo CHAT_ENDED; ?>;
		displayNewLine();
		<?
		if ($_SWIFT["settings"]["ls_depname"] == 1 && !empty($_SWIFT["departmentcache"][$_chatobject["departmentid"]]["title"]))
		{
			?>
			displayMessage("<?php echo sprintf($_SWIFT["language"]["chatleave"], $_chatobject["departmenttitle"]); ?><BR /><a href='<?php echo $_SWIFT["swiftpath"]; ?>visitor/index.php?_m=livesupport&_a=startclientchat&sessionid=<?php echo $_REQUEST["sessionid"]; ?>&leavemessage=1&departmentid=<?php echo $_chatobject["departmentid"]; ?>' target='_top'><?php echo $_SWIFT["language"]["chatendleavemsg"]; ?></a>");
			<?
		} else {
			?>
			displayMessage("<?php echo sprintf($_SWIFT["language"]["chatleave"], $_chatobject["staffname"], $_chatobject["departmenttitle"]); ?><BR /><a href='<?php echo $_SWIFT["swiftpath"]; ?>visitor/index.php?_m=livesupport&_a=startclientchat&sessionid=<?php echo $_REQUEST["sessionid"]; ?>&leavemessage=1&departmentid=<?php echo $_chatobject["departmentid"]; ?>' target='_top'><?php echo $_SWIFT["language"]["chatendleavemsg"]; ?></a>");
			<?
		}
		?>

		stopTimer();
	}
	<?
	}
	echo $messagejs;

	if (!empty($messagejs))
	{
/*		$fp = fopen("./cache/jscachetemp.txt", "a+");
		fwrite($fp, "---- BEGIN MESSAGE JS [". date("d M Y h:i:s A", DATENOW) ."] (". $_chatobject["chatobjectid"] ." - ". $_chatobject["userfullname"] .") ----\n".$messagejs."---- END MESSAGE JS ----\n");
		fclose($fp);*/
	}
	?>

	if (chatstatus != <?php echo CHAT_ENDED; ?>)
	{
		<?
		if ($noloop != true)
		{
		} else {
			?>
			doClientLoop = false;
			<?
		}
		?>
	} else if (chatstatus == <?php echo CHAT_ENDED;?>) {
		doClientLoop = false;
	}
	
}
